#pragma once
#include <iostream>
#include <string>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <functional>
#include "log.hpp"

using func_t = std::function<std::string(const std::string&)>;
//typedef std::function<std::string(const std::string&)> func_t;

enum
{
    SOCKET_ERR = 1,
    BIND_ERR,
};
extern Log log;
std::string defaultip = "0.0.0.0";
uint16_t defaultport = 8080;
const int size = 1024;
class UdpServer
{
public:
    UdpServer(const uint16_t &port = defaultport, const std::string &ip = defaultip) 
    : sockfd_(0),port_(port), ip_(ip),isrunning_(false)
    {
    }
    void Init()
    {
        // 1.创建udp socket
        sockfd_ = socket(AF_INET, SOCK_DGRAM, 0);
        if (sockfd_ < 0)
        {
            log(Fatal, "socket create error %d", sockfd_);
            exit(SOCKET_ERR);
        }
        log(Info, "socket create success %d", sockfd_);
        // 2.bind socket
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port_);
        local.sin_addr.s_addr = inet_addr(ip_.c_str());
        // local.sin_addr.s_addr = htonl(INADDR_ANY);
        int n=bind(sockfd_,(const struct sockaddr*)&local,sizeof(local));
        if(n<0)
        {
            log(Fatal,"bind error,errno:%d,err string:%s",errno,strerror(errno));
            exit(BIND_ERR);
        }
        log(Info,"bind success,errno:%d,err string:%s",errno,strerror(errno));
    }
    void Run(func_t func)
    {
        isrunning_=true;
        char inbuffer[size];
        while(isrunning_)
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            ssize_t n = recvfrom(sockfd_,inbuffer,sizeof(inbuffer)-1,0,(struct sockaddr*)&client,&len);
            if(n<0)
            {
                log(Warning,"recvfrom error,errno:%d,err string:%s",errno,strerror(errno));
                continue;
            }
            std::string info=inbuffer;
            //std::string echo_string="serve echo#" + info;
            std::string echo_string = func(info);
            sendto(sockfd_,echo_string.c_str(),echo_string.size(),0,(const sockaddr*)&client,len);
        }
    }
    ~UdpServer()
    {
        if(sockfd_<0)   close(sockfd_);
    }

private:
    int sockfd_;    // 网络文件描述符
    std::string ip_; // 任意IP地址 bind 0
    uint16_t port_; // 服务器端口号
    bool isrunning_;
};
